#include "StdAfx.h"
#include "ClientManager.hpp"


bool HpsFramework::Network::ClientManager::removeClient( Client::IdType id )
{
	ScopeLock ( _locker )

	if(this->_clientmap.find(id) != this->_clientmap.end()) 
	{

		this->_clientmap[id] = NULL;

		StartListIteration(Client*, this)
		{
			Client* temp = CurrentNode->getContent();
			if(temp)
			{
				if(temp->getId() == id)
				{
					this->remove(temp);
					StopListIteration();
				}
			}
			CurrentNode = GetNextNode();
		}
		FinishListIteration()

		return true;

	}

	return false;
}

bool HpsFramework::Network::ClientManager::removeClient( Client* instance )
{
	ScopeLock ( _locker )

	if(instance) 
	{
		this->_clientmap[instance->getId()] = NULL;
		return this->remove(instance);
		return true;
	}

	return false;
}

bool HpsFramework::Network::ClientManager::insertClient( Client* instance )
{

	ScopeLock ( _locker )

	if(instance) 
	{
		this->addLast ( instance );
		this->_clientmap[instance->getId()] = instance;
		return true;
	}

	return false;
}

HpsFramework::Network::Client* HpsFramework::Network::ClientManager::getById( Client::IdType id )
{

	ScopeLock ( _locker )

	if(this->_clientmap.find(id) == this->_clientmap.end())
		return NULL;

	Client* temp = this->_clientmap[id];
	if(temp) {
		return temp;
	}

	return NULL;

}

bool HpsFramework::Network::ClientManager::getById( Client::IdType id, Client*& client )
{
	ScopeLock ( _locker )

	if(this->_clientmap.find(id) == this->_clientmap.end())
		return false;

	Client* temp = this->_clientmap[id];
	if(temp) 
	{
		client = temp;
		return true;
	}

	return false;
}

HpsFramework::Network::ClientManager::~ClientManager( void )
{
	this->clear();
}

HpsFramework::Network::ClientManager::ClientManager( void )
{
#ifdef HPS_USE_GOOGLEHASH
	_clientmap.set_deleted_key(-2);
	_clientmap.set_empty_key(-1);
#endif
}

bool HpsFramework::Network::ClientManager::broadcast( byteptr buffer, size bufSize )
{
	StartListIteration(Client*, this)
	{
		if(CurrentNode->getContent())
		{
			CurrentNode->getContent()->write ( buffer, bufSize );
		}
		CurrentNode = GetNextNode();
	}
	FinishListIteration()
	return true;
}
